// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const { ccclass, property } = cc._decorator;

@ccclass
export default class ActivityScheduler extends cc.Component {

    //结束时间
    _endTs: number = 0;

    //时间是否已经到了，回调是否已经调用
    _called: boolean = false;

    //回调
    _callback: Function = null;

    //设置时间结束 要做的回调
    setAlarmClock(endTime: number, callback: Function) {
        cc.log("结束时间为:", new Date(endTime));
        this._endTs = endTime;

        this._called = false;

        this._callback = callback;

        this.unschedule(this.scheduleCheckEndTime);
        this.unschedule(this.scheduleAccurateEndTime);
        this.schedule(this.scheduleCheckEndTime, 30);
        this.scheduleCheckEndTime();
    }

    scheduleCheckEndTime() {
        cc.log("进入倒计时");
        let now = Date.now();  //准确时间戳

        if (now >= this._endTs && !this._called) {
            cc.log("倒计时结束，调用回调！");
            this._callback && this._callback();
            this._called = true;

            this.unschedule(this.scheduleCheckEndTime);
        } else {
            //若离结束只有30秒不到
            if (this._endTs - now <= 30 * 1000 && !this._called) {
                this.unschedule(this.scheduleCheckEndTime);
                this.schedule(this.scheduleAccurateEndTime, 1);
                this.scheduleAccurateEndTime();
            }
        }
    }

    scheduleAccurateEndTime() {
        cc.log("进入精确倒计时");
        let now = Date.now();  //准确时间戳
        if (now >= this._endTs && !this._called) {
            cc.log("倒计时结束，调用回调！");
            this._callback && this._callback();
            this._called = true;

            this.unschedule(this.scheduleAccurateEndTime);
        }
    }

    onDestroy() {
        this.unschedule(this.scheduleCheckEndTime);
        this.unschedule(this.scheduleAccurateEndTime);
    }

    // update (dt) {}
}
